package com.bs.bszhsq.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.bs.bszhsq.entity.Users;
import com.bs.bszhsq.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.condition.RequestConditionHolder;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class TokenUtils {



    @Autowired
    private IUsersService usersService;
   //在静态方法中，只能调用静态对象
   //Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的初始化方法)
   //该注解的功能：当依赖注入完成后用于执行初始化的方法，并且只会被执行一次

    @PostConstruct
    @Lazy
    public void setStaticuserserivce(){
        staticuserserivce=usersService;
    }

    private static IUsersService staticuserserivce;

    /**
     * 生成token
     * @param userId
     * @param sign
     * @return
     */
    public static String getToken(String userId, String sign) {
        //将userid保存到token作为载荷
       return JWT.create()
                .withAudience(userId)
                .withExpiresAt(DateUtil.offsetHour(new Date(), 12))//2小时token过期
                .sign(Algorithm.HMAC256(sign));//以password作为token密钥
    }

    /**
     * 获取当前用户登录信息
     * @return
     */
    // todo 待解决
    public static Users getCurrentUser(){
        //拿到token，解析出里面的user信息
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token)){
                String userId = JWT.decode(token).getAudience().get(0);
                return staticuserserivce.getById(userId);
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }


}
